package dao.workdao;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;

import dao.basedao.DBManager;
import util.DateTool;

import model.Work;

public class WorkDaoImpl implements WorkDao {

	@Override
	public boolean save(Work work) throws IllegalAccessException, ClassNotFoundException, Exception {
		boolean flag =false;
		Connection con=DBManager.getConn();
		PreparedStatement ps=con.prepareStatement("insert into releasework(title,content,releasedate,deadline,author_id) values (?,?,?,?,?)");
		ps.setString(1, work.getTitle());
		ps.setString(2,work.getContent());
		java.sql.Date releaseDate=DateTool.JavaDatetoSqlDate(work.getReleasedate());	
		java.sql.Date deadline=DateTool.JavaDatetoSqlDate(work.getDeadline());
		
		ps.setDate(3, releaseDate);
		ps.setDate(4,deadline);
		ps.setString(5, work.getAuthor_id());
		int rs=ps.executeUpdate();
		if(rs>0)
			flag=true;
		ps.close();
		DBManager.closeConn(con);
		return flag;
	}

	@Override
	public ArrayList<Work> queryAllWork() throws IllegalAccessException, ClassNotFoundException, Exception{
		ArrayList<Work> WorkList = new ArrayList<Work>();
	   Connection con=DBManager.getConn();
	
		Statement ps = con.createStatement();
		ResultSet rs=ps.executeQuery("select * from releasework order by work_id desc");
		while(rs.next()){
			Work work=new Work();
			work.setWork_id(rs.getInt("work_id"));
			work.setTitle(rs.getString("title"));
			work.setContent(rs.getString("content"));
			java.util.Date releaseDate= DateTool.SqlDatetoJavaDate(rs.getDate("releasedate"));
			java.util.Date deadline=DateTool.SqlDatetoJavaDate(rs.getDate("deadline"));
			work.setReleasedate(releaseDate);
			work.setDeadline(deadline);
			WorkList.add(work);
		}
		rs.close();
		ps.close();
		DBManager.closeConn(con);
		return WorkList;
	}

	@Override
	public Work querySingleWork(int work_id) throws IllegalAccessException, ClassNotFoundException, Exception {
		Work work=new Work();
	    Connection con=DBManager.getConn();
		
		PreparedStatement ps=con.prepareStatement("select * from releasework where work_id=?");
	    ps.setInt(1, work_id);
	    ResultSet rs=ps.executeQuery();
	    while(rs.next()){
	    	work.setWork_id(work_id);
	    	work.setTitle(rs.getString("title"));
	    	work.setContent(rs.getString("content"));
	    	java.util.Date releaseDate= DateTool.SqlDatetoJavaDate(rs.getDate("releasedate"));
			java.util.Date deadline=DateTool.SqlDatetoJavaDate(rs.getDate("deadline"));
	    	work.setReleasedate(releaseDate);
	    	work.setDeadline(deadline);
	    	//work.setAuthor_id(rs.getString("author_id"));
	    }
	    rs.close();
	    ps.close();
	    DBManager.closeConn(con);
	    return work;
	}
   
}
